<template>
    <tn-image-upload @remove="remove" class="up" :limit="props.limit" v-model="imageList" :action="actionUrl"
        :custom-upload-handler="uploadHandle" />
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import type {
    ImageUploadCustomFunction,
    ImageUploadFile,
} from '@tuniao/tnui-vue3-uniapp'
import { BASE_URL } from '@/config/base'


const props = defineProps<{
    limit: number,
    type?: number
}>()

const emit = defineEmits(['upload'])

// props.imgs?.length ? props.imgs.join(',') : 
const imageList = ref<string[]>([])
const imageUrlList = ref<string[]>([])
// console.log(imageUrlList.value, 'imageUrlList')
// console.log(imageList.value, 'imageList')

onMounted(() => {
    if (props.type == 1) {
        imageList.value = uni.getStorageSync('imgs').split(',')
        imageUrlList.value = uni.getStorageSync('imgs').split(',')
    }

})

const actionUrl = BASE_URL + "/index.php/api/upload/temporary"

const uploadHandle: ImageUploadCustomFunction = (file: ImageUploadFile) => {
    return new Promise((resolve, reject) => {
        const url = (file as UniApp.ChooseImageSuccessCallbackResultFile).path
        uni.uploadFile({
            url: actionUrl,
            filePath: url,
            name: 'file',
            header: {
                "Content-Type": "multipart/form-data",
            },
            formData: {
                type: "picture",
            },
            success: (res) => {
                const data = JSON.parse(res.data)
                resolve(data.data.url)
                imageUrlList.value.push(data.data.url)
                emit('upload', imageUrlList.value.join(','))
            },
            fail: (err) => {
                reject(err)
            },
        })
    })
}

// 删除图片
const remove = (url: string) => {
    imageUrlList.value = imageUrlList.value.filter(item => item != url)
    emit('upload', imageUrlList.value.join(','))
}
</script>
<style lang="scss" scoped>
.up {
    background-color: red;
}
</style>